package com.gomore.opple.module.login;

import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.gomore.opple.R;
import com.gomore.opple.module.BaseFragment;
import com.gomore.opple.module.IntentStart;
import com.gomore.opple.utils.DeviceUtils;
import com.gomore.opple.utils.DialogUtils;
import com.gomore.opple.utils.UpdateManager;
import com.gomore.opple.web.cgform.app.entity.TOAppversionEntity;

import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.Bind;
import butterknife.OnClick;


/**
 * Created by robot
 */
public class LoginFragment extends BaseFragment implements LoginContract.View {
    //登录界面
    @Bind(R.id.login_layout)
    RelativeLayout login_layout;
    @Bind(R.id.user_name)
    EditText user_name;
    @Bind(R.id.password)
    EditText password;
    @Bind(R.id.forget_password)
    TextView forget_password;
    @Bind(R.id.login)
    TextView login;
    //身份验证
    @Bind(R.id.mobile_layout)
    RelativeLayout mobile_layout;
    @Bind(R.id.mobile_back)
    TextView mobile_back;
    @Bind(R.id.mobile_user_name)
    EditText mobile_user_name;
    @Bind(R.id.mobile)
    EditText mobile;
    @Bind(R.id.send_code)
    TextView send_code;
    @Bind(R.id.code)
    EditText code;
    @Bind(R.id.mobile_next)
    TextView mobile_next;
    //重置密码
    @Bind(R.id.password_layout)
    RelativeLayout password_layout;
    @Bind(R.id.password_back)
    TextView password_back;
    @Bind(R.id.first_password)
    EditText first_password;
    @Bind(R.id.second_password)
    EditText second_password;
    @Bind(R.id.password_next)
    TextView password_next;

    private LoginContract.Presenter mPresenter;
    //短信验证码
    private TimerTask timerTask;
    private int recordTime;

    public static LoginFragment getInstance() {
        return new LoginFragment();
    }

    @Override
    protected int getLayoutView() {
        return R.layout.fragment_login;
    }

    @Override
    protected void initalizeData() {
        String version = DeviceUtils.getVersionName(getActivity());
        if (!TextUtils.isEmpty(version)) {
            mPresenter.checkUpdate("apk", version);
        }
    }

    @Override
    protected void initalizeViews() {
        mPresenter.prepareInitData();
    }


    @Override
    public void setPresenter(LoginContract.Presenter presenter) {
        mPresenter = presenter;
    }

    @Override
    public void showProgressDialog() {
        DialogUtils.showLoadingDialog(getActivity(), getResources().getString(R.string.loading));
    }

    @Override
    public void hideProgressDialog() {
        DialogUtils.closeLoadingDialog();
    }

    @Override
    public void showMessage(String msg) {
        showToast(msg);
    }

    @Override
    public void gotoMainActivity() {
        IntentStart.getInstance().startMainActivity(getActivity());
    }

    @Override
    public void showMessage(int msgId) {
        showToast(msgId);
    }

    @Override
    public void initView(String userName, String password2) {
        user_name.setText(userName);
        password.setText(password2);
    }

    /**
     * 展示版本更新对话框
     *
     * @param version 服务器版本信息
     */
    @Override
    public void showUpdateDialog(TOAppversionEntity version) {
        new UpdateManager(getActivity(), false).displayUpdateDialog(version);
    }

    @Override
    public void goToLogin() {
        login_layout.setVisibility(View.VISIBLE);
        mobile_layout.setVisibility(View.GONE);
        password_layout.setVisibility(View.GONE);
    }

    @OnClick({R.id.login, R.id.forget_password, R.id.mobile_back, R.id.mobile_next,
            R.id.password_back, R.id.password_next, R.id.send_code})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.login:
                mPresenter.login(user_name.getText().toString().trim(), password.getText().toString().trim());
                break;
            case R.id.forget_password:
                login_layout.setVisibility(View.GONE);
                mobile_layout.setVisibility(View.VISIBLE);
                password_layout.setVisibility(View.GONE);
                break;
            case R.id.mobile_back:
                login_layout.setVisibility(View.VISIBLE);
                mobile_layout.setVisibility(View.GONE);
                password_layout.setVisibility(View.GONE);
                break;
            case R.id.mobile_next:
                if (TextUtils.isEmpty(mobile_user_name.getText().toString().trim())) {
                    showMessage(R.string.hint_name_empty);
                    return;
                }
                if (TextUtils.isEmpty(mobile.getText().toString().trim())) {
                    showMessage(R.string.hint_mobile);
                    return;
                }
                if (TextUtils.isEmpty(code.getText().toString().trim())) {
                    showMessage(R.string.hint_code);
                    return;
                }
                login_layout.setVisibility(View.GONE);
                mobile_layout.setVisibility(View.GONE);
                password_layout.setVisibility(View.VISIBLE);
                break;
            case R.id.password_back:
                login_layout.setVisibility(View.GONE);
                mobile_layout.setVisibility(View.VISIBLE);
                password_layout.setVisibility(View.GONE);
                break;
            case R.id.password_next:
                if (TextUtils.isEmpty(first_password.getText().toString().trim()) ||
                        TextUtils.isEmpty(second_password.getText().toString().trim())) {
                    showMessage(R.string.hint_password_empty);
                    return;
                }
                if (!first_password.getText().toString().trim().equals(second_password.getText().toString().trim())) {
                    showMessage(R.string.unequals);
                    return;
                }
                mPresenter.resetPassword(mobile_user_name.getText().toString().trim(), code.getText().toString().trim(),
                        first_password.getText().toString().trim());
                break;
            case R.id.send_code:
                if (!isPhoneNumberValid(mobile.getText().toString().trim())) {
                    showMessage(R.string.mobile_true);
                    return;
                }
                mPresenter.sendCode(mobile.getText().toString().trim(), mobile_user_name.getText().toString().trim());
                //开启计时任务
                starTimer();
                break;
        }
    }

    //判断是否为电话号码
    private boolean isPhoneNumberValid(String phoneNumber) {
        boolean isValid = false;
        String expression = "((^(13|14|15|17|18)[0-9]{9}$)|(^0[1,2]{1}\\d{1}-?\\d{8}$)|(^0[3-9] {1}\\d{2}-?\\d{7,8}$)|(^0[1,2]{1}\\d{1}-?\\d{8}-(\\d{1,4})$)|(^0[3-9]{1}\\d{2}-? \\d{7,8}-(\\d{1,4})$))";
        CharSequence inputStr = phoneNumber;
        Pattern pattern = Pattern.compile(expression);
        Matcher matcher = pattern.matcher(inputStr);
        if (matcher.matches()) {
            isValid = true;
        }
        return isValid;
    }

    /**
     * 开启计时
     */
    private void starTimer() {
        timerTask = new TimerTask() {
            @Override
            public void run() {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        recordTime++;
                        if (recordTime == 60) {
                            if (timerTask != null) {
                                timerTask.cancel();
                            }
                            send_code.setText(getActivity().getResources().getString(R.string.send));
                        } else {
                            int have = 60 - recordTime;
                            send_code.setText("( " + have + "S )");
                        }
                    }
                });
            }
        };
        Timer recordTimer = new Timer(true);
        recordTimer.schedule(timerTask, 0, 1000);
    }
}
